package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.AsyncHttpRequest;
import com.loopj.ohos.http.AsyncHttpResponseHandler;
import com.loopj.ohos.http.ResponseHandlerInterface;
import com.loopj.ohos.http.ext.LocalHiLog;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.client.methods.HttpUriRequest;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.protocol.HttpContext;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.app.Context;
import ohos.eventhandler.EventRunner;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static com.loopj.ohos.http.sample.IntentServiceSample.LOG_TAG;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class ExampleOhosTest {
    private static final String TAG = "TestAsyncHttp";
    @Test
    public void testBundleName() {
        final String actualBundleName = AbilityDelegatorRegistry.getArguments().getTestBundleName();
        assertEquals("com.loopj.android.http.sample", actualBundleName);
    }

    @Before
    public void setUp() {
        LocalHiLog.info(TAG, "setUp");
        EventRunner.create();
    }

    @Test
    public void testGet() {
        final Boolean[] resultFlg = {false};
        final CountDownLatch signal = new CountDownLatch(1);
        LocalHiLog.info(TAG, "before request");
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient() {
            @Override
            protected AsyncHttpRequest newAsyncHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
                return super.newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context);
            }
        };

        AbilityDelegatorRegistry.getAbilityDelegator().runOnUIThreadSync(new Runnable() {
            @Override
            public void run() {
                asyncHttpClient.get(AbilityDelegatorRegistry.getAbilityDelegator().getAppContext(), "https://httpbin.org/get", null, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        assertEquals(200, statusCode);
                        LocalHiLog.info(TAG, "onSuccess");
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        LocalHiLog.info(TAG, "onFailure");
                    }
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        LocalHiLog.info(TAG, "onFinish");
                        assertNull(null);
                        signal.countDown();
                        resultFlg[0] = true;
                    }
                });
            }
        });

        try {
            LocalHiLog.info(TAG, "signal.await");
            signal.await(30, TimeUnit.SECONDS); // wait for callback
        } catch (InterruptedException e) {
            LocalHiLog.info(LOG_TAG, e.getMessage());
        }
        assertTrue(resultFlg[0]);
        assertEquals(0, signal.getCount());
    }

    @Test
    public void testPost() {
        final Boolean[] resultFlg = {false};
        final CountDownLatch signal = new CountDownLatch(1);
        LocalHiLog.info(TAG, "before request");
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient() {
            @Override
            protected AsyncHttpRequest newAsyncHttpRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) {
                return super.newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context);
            }
        };

        AbilityDelegatorRegistry.getAbilityDelegator().runOnUIThreadSync(new Runnable() { // THIS IS THE KEY TO SUCCESS
            @Override
            public void run() {
                asyncHttpClient.post(AbilityDelegatorRegistry.getAbilityDelegator().getAppContext(), "https://httpbin.org/post", null, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        assertEquals(200, statusCode);
                        LocalHiLog.info(TAG, "onSuccess");
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        LocalHiLog.info(TAG, "onFailure");
                    }
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        LocalHiLog.info(TAG, "onFinish");
                        assertNull(null);
                        signal.countDown();
                        resultFlg[0] = true;
                    }
                });
            }
        });

        try {
            signal.await(30, TimeUnit.SECONDS); // wait for callback
        } catch (InterruptedException e) {
            LocalHiLog.info(LOG_TAG, e.getMessage());
        }
        assertTrue(resultFlg[0]);
        assertEquals(0, signal.getCount());
    }

}